« Gold Phoenix Technology wishes us a Merry Christmas | Main | TC64x based fan controllers »

Fading LED default test sketch (February 12, 2009)

For some time now, every Arduino bootloaded ATmega we've shipped has come with a default testing sketch that slowly pulses the LED on and off in a cyclic fashion.

A "fading" sketch using hardware PWM is included in the IDE distribution under ExamplesAnalogFading to fade an LED, but the Pin 13 status LED isn't connected to a hardware PWM pin.

The answer is to abuse the delayMicroseconds call to create crude software PWM. By setting the pin high; delaying; setting the pin off; and delaying for a different period, we can change the brightness simply by altering the delay.

One catch to this approach, is if you use purely the on/off delay to control the PWM speed, you're left with either a very fast fade or an unsettling flashing. Instead we keep the delay between 4 and 250 µs (about 3 to 4kHz) and add an additional loop around each on/off loop to set the fading speed. --You can't set the delayMicroseconds code to 0 or you'll get an unexpectedly long delay.

Finally, we use the serial port to output a rising count, just to ensure the serial port works.

// Fading LED
// by Spiffed <https://spiffie.org/>;
// original by BARRAGAN <;

int value = 0;
int rep = 0;
int ledpin = 13;
int count = 0;  // light connected to digital pin 9

void setup()
{
 Serial.begin(9600);
 pinMode(ledpin,OUTPUT);
}

void loop()
{
 for(value = 4 ; value <= 250; value++)  // fade in (from min to max)
 {
   for(rep=0;rep <= 10;rep++){
   digitalWrite(ledpin, HIGH);  // sets the value (range from 0 to 255)
   delayMicroseconds(value);  // waits for 30 milli seconds to see the dimming effect
   digitalWrite(ledpin, LOW);
   delayMicroseconds((255-value));
   }
 }
 Serial.println(count);
 count++;
 for(value = 250; value >=4; value--)  // fade out (from max to min)
 {
   for(rep=0;rep <= 10;rep++){
   digitalWrite(ledpin, HIGH);  // sets the value (range from 0 to 255)
   delayMicroseconds(value);  // waits for 30 milli seconds to see the dimming effect
   digitalWrite(ledpin, LOW);
   delayMicroseconds(255-value);
   }
  }
}


Posted by spiffed at February 12, 2009 11:11 AM